/**
 * @author caslyn
 */
	$(document).ready(function(){
		
		var schoolid = $('#schoolid'),
			semesterid = $('#semesterid'),
			name = $("#name"),
			year = $("#year"),
			fromdate = $("#fromdate"),
			todate = $("#todate"),
			schooldesc = $('#schooldesc'),
			selPresident = $('#selPresident'),
			allFields = $([]).add(name).add(year).add(fromdate).add(todate),
			new_name = $("#new_name"),
			new_year = $("#new_year"),
			new_fromdate = $("#new_fromdate"),
			new_todate = $("#new_todate"),
			new_allFields = $([]).add(new_name).add(new_year).add(new_fromdate).add(new_todate),
			tips = $("#validateTips"),
			new_tips = $("#new_validateTips"),
			pageid = $('#pageid');
			

		function updateTips(t) {
			tips.text(t).effect("highlight",{},1500);
			new_tips.text(t).effect("highlight",{},1500);
		}

		function checkLength(o,n,min,max) {

			if ( o.val().length > max || o.val().length < min ) {
				o.addClass('ui-state-error');
				updateTips("Length of " + n + " must be between "+min+" and "+max+".");
				return false;
			} else {
				return true;
			}

		}

		function checkRegexp(o,regexp,n) {

			if ( !( regexp.test( o.val() ) ) ) {
				o.addClass('ui-state-error');
				updateTips(n);
				return false;
			} else {
				return true;
			}

		}
		
		$("#dialog").dialog({
			bgiframe: true,
			autoOpen: false,
//			height: 300,
			modal: true,
			buttons: {
				'Save': function() {
					var bValid = true;
					allFields.removeClass('ui-state-error');

					bValid = bValid && checkLength(name,"name",1,100);
					bValid = bValid && checkLength(year,"year",4,4);
//					bValid = bValid && checkLength(fromdate,"fromdate",5,16);
//					bValid = bValid && checkLength(todate,"todate",5,16);

		//			bValid = bValid && checkRegexp(name,/^(\w)+$/i,"Name must not be empty.");
					// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/year_address_validation/
//					bValid = bValid && checkRegexp(email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"eg. ui@jquery.com");
//					bValid = bValid && checkRegexp(password,/^([0-9a-zA-Z])+$/,"Password field only allow : a-z 0-9");
					bValid = bValid && checkRegexp(fromdate,/^\d\d\d\d-\d\d-\d\d+$/,"Date must be in : YYYY-MM-DD");
					bValid = bValid && checkRegexp(todate,  /^([0-9][0-9][0-9][0-9]\-[0-9][0-9]\-[0-9][0-9])+$/,"Date must be in : YYYY-MM-DD");
					
					if (bValid) {
						$('#semesterinfo').text(name.val() + ' (' + fromdate.val() + ' to ' + todate.val() + ')');
						$.post("json.php",{"task": "saveSemester",
						"id":semesterid.val(),"name":name.val(),"year":year.val(),
						"fromdate":fromdate.val(),"todate":todate.val()} , 
							function(data){
								alert ('Semester saved.');
//								$(this).dialog('close');
							}
						);
						$(this).dialog('close');
					}
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			},
			close: function() {
				allFields.val('').removeClass('ui-state-error');
			}
		});
		
		$("#dialog_add_new_semester").dialog({
			bgiframe: true,
			autoOpen: false,
			modal: true,
			buttons: {
				'Save': function() {
					var bValid = true;
					new_allFields.removeClass('ui-state-error');

					bValid = bValid && checkLength(new_name,"name",1,100);
					bValid = bValid && checkLength(new_year,"year",4,4);

					bValid = bValid && checkRegexp(new_fromdate,/^\d\d\d\d-\d\d-\d\d+$/,"Date must be in : YYYY-MM-DD");
					bValid = bValid && checkRegexp(new_todate,  /^([0-9][0-9][0-9][0-9]\-[0-9][0-9]\-[0-9][0-9])+$/,"Date must be in : YYYY-MM-DD");
					
					if (bValid) {
						$.post("json.php",{"task": "addNewSemester",
						"id":schoolid.val(),"name":new_name.val(),"year":new_year.val(),
						"fromdate":new_fromdate.val(),"todate":new_todate.val()} , 
							function(data){
								$('#semesterinfo').text(new_name.val() + ' (' + new_fromdate.val() + ' to ' + new_todate.val() + ')');
								alert ('Semester saved.');
								$("#dialog_add_new_semester").dialog('close');
							}
						);
//						$(this).dialog('close');
					}
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			},
			close: function() {
				new_allFields.val('').removeClass('ui-state-error');
			}
		});

		$("#dialog_school_desc").dialog({
			bgiframe: true,
			autoOpen: false,
//			height: 300,
			width: 500,
			modal: true,
			buttons: {
				'Save': function() {
					schooldesc.removeClass('ui-state-error');
					
					if (schooldesc.val().length >0 ) {
						temp = schooldesc.val();
						temp = temp.replace(/\n/g,"<br>");
//						$('#spnSchoolDesc').text(schooldesc.val());
						$.post("json.php",{"task": "saveSchoolDesc",
						"id":schoolid.val(),"description": temp } , 
							function(data, textStatus){
//								alert(textStatus);
								if(textStatus == "success") {
									$('#spnSchoolDesc').empty();
									$('#spnSchoolDesc').append(temp);
									alert ('Save success. ');
								} else {
									alert ('Save error: ' + data);
								}
							}
						);
					} 
					$(this).dialog('close');
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			},
			close: function() {
				schooldesc.val('').removeClass('ui-state-error');
			}
		});
		
		$("#dialog_school_pic").dialog({
			bgiframe: true,
			autoOpen: false,
//			height: 300,
//			width: 500,
			modal: true,
			buttons: {
				'Save': function() {
					$.post("json.php",{"task": "saveSchoolPic",
					"id":selPresident.val(),"schoolid": schoolid.val() } , 
						function(data, textStatus){
							if(textStatus == "success") {
								$('#spnPresident').text(selPresident.children(':selected').text());
								alert ('Save success. ');
							} else {
								alert ('Save error: ' + data);
							}
						}
					);
					$(this).dialog('close');
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			},
			close: function() {
//				schooldesc.val('').removeClass('ui-state-error');
			}
		});

	$('a.ui-corner-all').hover(
		function(){ 
			$(this).addClass("ui-state-hover"); 
		},
		function(){ 
			$(this).removeClass("ui-state-hover"); 
		}
	).mousedown(function(){
		$(this).addClass("ui-state-active"); 
	})
	.mouseup(function(){
			$(this).removeClass("ui-state-active");
	});

		
		$('#editSchoolPic').click(function() {
			selPresident.empty();
			$.getJSON("json.php",{task: "getPresidentCandidates", id: schoolid.val()},
				function(data){
					$.each(data.candidates, function(i,item){ 
			            selPresident.append('<option value="' + item.id + '">' + item.name + '</option>');
          			}); 
					$('#dialog_school_pic').dialog('open');
				}
			);
//			$('#dialog_school_pic').dialog('open');
		});
		
		$('#editSchoolDesc').click(function() {
			x = $('#spnSchoolDesc').html();
			schooldesc.val(x.replace(/<br>/g,"\n").replace(/<br\/>/g,"\n"));
			$('#dialog_school_desc').dialog('open');
		});
		
		
		$('#edit_semester').click(function() {
//			load json data
			try {
				$.getJSON("json.php", {
					task: "currentsemester",
					id: schoolid.val()
				}, function(data, statusText){
					semesterid.val(data.id);
					name.val(data.name);
					year.val(data.year);
					fromdate.val(data.fromdate);
					todate.val(data.todate);
					$('#dialog').dialog('open');
				});
			} catch(e) {
				alert(e.getMessage);
			}
//			$('#dialog').dialog('open');
		});

		$('#addNewSemester').click(function() {
			$('#dialog_add_new_semester').dialog('open');
		});

		$('#addSchoolNotice').click(function() {
			$('#dialog-newnotice').dialog('open');
		});
		
		$("#dialog-newnotice").dialog({
			bgiframe: true,
			autoOpen: false,
//			height: 300,
			width: 490,
			modal: true,
			buttons: {
				'Save': function() {
					temp = $('#new_notice_content').val();
					temp = temp.replace(/\n/g,"<br>");
					$.getJSON("json.php", { "task": "addNewNotice",
					"pageid":pageid.val(), "subject": $('#new_notice_subject').val(),
					"content": temp, "schoolid": schoolid.val() } , 
						function(data){
							$('#noticelist').prepend('<span id="spnnotice' + data.id + '"><b>' + data.subject + 
							'</b><br/><span>' +
							data.content + '</span> ' +
							WriteActionButton("Edit", "editNotice(" + data.id + ")") + ' ' +
							WriteActionButton("Delete", "deleteNotice(" + data.id + ")") +
							'<hr/></span>' );
//							alert('Save success. ');
							$("#dialog-newnotice").dialog('close');
						}
					);
//					$(this).dialog('close');
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			},
			close: function() {
				$('#new_notice_subject').val('');
				$('#new_notice_content').val('');
			}
		});

		$("#dialog_editnotice").dialog({
			bgiframe: true,
			autoOpen: false,
//			height: 300,
			width: 490,
			modal: true,
			buttons: {
				'Save': function() {
					temp = $('#edit_notice_content').val();
					temp = temp.replace(/\n/g,"<br>");
					$.getJSON("json.php", { "task": "saveNewNotice", "id": $('#edit_notice_id').val(),
					"pageid":pageid.val(), "subject": $('#edit_notice_subject').val(),
					"content": temp, "schoolid": schoolid.val() } , 
						function(data){
//							spanname = '#spnnotice' + data.id;
							$('#spnnotice' + data.id).children('span').html(data.content);
							$('#spnnotice' + data.id).children('b').html(data.subject);
//							$('#spnnotice' + data.id).html('<b>' + data.subject + '</b><br/>' +
//							data.content + ' ' +
//							WriteActionButton("Edit", "editNotice('" + data.id + "')") + ' ' +
//							WriteActionButton("Delete", "deleteNotice('" + data.id + "')") +
//							'<hr/>' );
							alert('Save success. ');
							$("#dialog_editnotice").dialog('close');
						}
					);
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			},
			close: function() {
				$('#edit_notice_subject').val('');
				$('#edit_notice_content').val('');
			}
		});
		
		$("#dialog_new_faculty").dialog({
			bgiframe: true,
			autoOpen: false,
			width: 490,
			modal: true,
			buttons: {
				'Save': function() {
					temp = $('#facluty_description').val();
					temp = temp.replace(/\n/g,"<br>");
					$.post("json.php", { "task": "addNewFaculty",
					"name": $('#faculty_name').val(), "schoolid": schoolid.val(),
					"description": temp, "pic": $('#chairperson').val() } , 
						function(data){
							$('#facultylist').append('<li id="lifaculty'+data+'">' +
								 $('#faculty_name').val() +
								 ' ' +
								WriteActionButton("View", "viewFaculty('" + data + "')" ) +
								' ' +
								WriteActionButton("Delete", "deleteFaculty('" + data + "')") +
								'</li>' );
							$("#dialog_new_faculty").dialog('close');
						}
					);
//					$(this).dialog('close');
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			},
			close: function() {
				$('#faculty_name').val('');
				$('#facluty_description').val('');
			}
		});

		$('#addFaculty').click(function(){
			$('#chairperson').empty();
			$.getJSON("json.php",{
				"task": "getPresidentCandidates",
				"id": schoolid.val()
			}, function(data){
				$.each(data.candidates, function(i,item){ 
		            $('#chairperson').append('<option value="' + item.id + '">' + item.name + '</option>');
       			}); 
			});
			$('#dialog_new_faculty').dialog('open');
		});

	});

function editNotice(nid){
	// load data from json
//	alert('Editing notice '+ id);
		temp = $('#spnnotice'+nid).children('span').html();
		temp = temp.replace(/<br>/g, "\n");
		$('#edit_notice_subject').val($('#spnnotice'+nid).children('b').html());
		$('#edit_notice_content').val(temp);
		$('#edit_notice_id').val(nid);
		// open edit dialog
		$('#dialog_editnotice').dialog('open');
}

function deleteNotice(noticeid){
	// ask user if want to delete
	var answer = confirm("Do you really want to delete this notice?");
	if(answer == true){
	// perform ajax  request
		$.post("json.php",{task:"deleteNotice",id:noticeid},
		function(data){
			if(data=="1"){
				alert("Notice deleted.");
				$('#spnnotice'+noticeid).remove();
			}
		});			
	}
	// show success.
}

function deleteFaculty(facid){
	var answer = confirm("Do you really want to delete this faculty?");
	if(answer == true){
	// perform ajax  request
		$.post("json.php",{task:"deleteFaculty",id:facid},
		function(data){
			if(data=="1"){
				alert("Faculty deleted.");
				$('#lifaculty'+facid).remove();
			}
		});			
	}
}

function viewFaculty(fid) {
//	alert('view faculty');
	$('#hiddentask').val('faculty');
	$('#hiddenid').val(fid);
	$('#hiddenform').submit();
}
